<template>
  <span :style="{ color, fontWeight, fontSize }">
    {{ value }}
  </span>
</template>
<script lang="ts">
import {
  defineComponent,
  ref,
  computed,
  watch,
  watchEffect,
  onMounted,
  unref,
} from "vue";
import { isNumber } from "../../utils/is";

const props = {
  startVal: { type: Number, default: 0 },
  endVal: { type: Number, default: 2021 },
  duration: { type: Number, default: 1500 },
  autoplay: { type: Boolean, default: true },
  decimals: {
    type: Number,
    default: 0,
    validator(value: number) {
      return value >= 0;
    },
  },
  prefix: { type: String, default: "" },
  suffix: { type: String, default: "" },
  separator: { type: String, default: "," },
  decimal: { type: String, default: "." },
  /**
   * font color
   */
  color: {
    type: String,
    default: "#161840",
  },
  fontWeight: {
    type: String,
    default: "bold",
  },
  fontSize: {
    type: String,
    default: "18px",
  },
  /**
   * Turn on digital animation
   */
  useEasing: { type: Boolean, default: true },
  /**
   * Digital animation
   */
  transition: { type: String, default: "linear" },
};

export default defineComponent({
  name: "CountTo",
  props,
  emits: ["onStarted", "onFinished"],
  setup(props, { emit }) {
    function useTransition(source: any, options: any = {}) {
      const {
        disabled = ref(false),
        duration = 1500,
        onFinished,
        onStarted,
      } = options;
      const outputValue = ref(source.value);

      watch(source, (newValue) => {
        if (!disabled.value) {
          // 开始动画时调用 onStarted 回调
          onStarted && onStarted();

          // 创建过渡动画效果
          let startTime = Date.now();
          let initialValue = outputValue.value;

          const step = () => {
            let elapsed = Date.now() - startTime;
            if (elapsed < duration) {
              // 计算插值，根据缓动公式或线性公式平滑过渡
              outputValue.value =
                initialValue + (newValue - initialValue) * (elapsed / duration);
              requestAnimationFrame(step); // 持续执行动画
            } else {
              // 动画结束，确保最终值是目标值
              outputValue.value = newValue;
              // 动画结束时调用 onFinished 回调
              onFinished && onFinished();
            }
          };

          step();
        } else {
          outputValue.value = newValue;
        }
      });

      return outputValue;
    }

    const source = ref(props.startVal);
    const disabled = ref(false);

    let outputValue = useTransition(source);
    const value = computed(() => formatNumber(unref(outputValue)));

    /**
     * watchEffect 也是一个帧听器，是一个副作用函数。 它会监听引用数据类型的所有属性，不需要具体到某个属性，一旦运行就会立即监听
     * watchEffect 在响应数据初始化时就会立即执行回调函数。
     */
    watchEffect(() => {
      source.value = props.startVal;
    });

    /**
     * watch 还可以监听数组，前提是这个数组内部含有响应式数据
     * watch 在响应数据初始化时是不会执行回调函数的
     */
    watch([() => props.startVal, () => props.endVal], () => {
      if (props.autoplay) {
        start();
      }
    });

    onMounted(() => {
      props.autoplay && start();
    });

    function start() {
      run();
      source.value = props.endVal;
    }

    function reset() {
      source.value = props.startVal;
      run();
    }

    function run() {
      outputValue = useTransition(source, {
        disabled,
        duration: props.duration,
        onFinished: () => emit("onFinished"),
        onStarted: () => emit("onStarted"),
      });
    }

    /**
     * 将数字转化为千位分隔符的形式
     * @param num
     */
    function formatNumber(num: number | string) {
      if (!num && num !== 0) {
        return "";
      }
      const { decimals, decimal, separator, suffix, prefix } = props;

      num = Number(num).toFixed(decimals);
      num += "";

      const x = num.split(".");
      let x1 = x[0];
      const x2 = x.length > 1 ? decimal + x[1] : "";

      const rgx = /(\d+)(\d{3})/;
      if (separator && !isNumber(separator)) {
        while (rgx.test(x1)) {
          x1 = x1.replace(rgx, "$1" + separator + "$2");
        }
      }
      return prefix + x1 + x2 + suffix;
    }

    return { value, start, reset };
  },
});
</script>
